<template>
  <div class="search">
    <el-select
      v-model="select"
      placeholder="Select"
      style="width: 100px; margin-right: 10px"
    >
      <el-option
        v-for="item in selectList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-input style="width: 200px; margin-right: 10px" v-model="key"></el-input>
    <el-button type="success" plain @click="search">搜索</el-button>
    <el-button type="primary" plain @click="addAccount = true"
      >添加读者信息</el-button
    >
  </div>
  <div v-if="accountList.isShow">
    <el-table :data="showList.list" border stripe style="width: 100%">
      <el-table-column prop="ReaderID" label="id" width="180" />
      <el-table-column prop="ReaderName" label="用户名" width="180" />
      <el-table-column prop="job" label="身份">
        <template #default="scope">
          <el-tag>{{ scope.row.job }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Debt" label="欠费" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleCheck(scope.$index, scope.row)"
            >查看借阅</el-button
          >
          <el-button
            size="small"
            type="success"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="修改用户" width="30%">
      <div class="borrow-body">
        <el-form
          :label-position="'right'"
          label-width="80px"
          style="max-width: 460px"
        >
          <el-form-item label="id">
            {{ accountInfo.data.ReaderID }}
          </el-form-item>
          <el-form-item label="用户名">
            {{ accountInfo.data.ReaderName }}
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              v-model="accountInfo.data.PhoneNumber"
              type="text"
            ></el-input>
          </el-form-item>
          <el-form-item label="权限">
            <el-select
              v-model="accountInfo.data.job"
              class="m-2"
              placeholder="Select"
            >
              <el-option
                :key="'TEACHER'"
                :label="'TEACHER'"
                :value="'TEACHER'"
              />
              <el-option
                :key="'STUDENT'"
                :label="'STUDENT'"
                :value="'STUDENT'"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="欠费">
            {{ accountInfo.data.Debt }}
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit"> 确定修改 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="borrowShow" title="用户借阅信息" width="60%">
      <el-table :data="showList.bookList" border stripe style="width: 100%">
        <el-table-column prop="ISBN" label="书号" width="180" />
        <el-table-column prop="bookname" label="书名" width="180" />
        <el-table-column prop="lendNum" label="借阅数目" />
        <el-table-column prop="LendDate" label="借阅日期" />
        <el-table-column prop="ReturnDate" label="归还时间" />
        <el-table-column label="是否归还">
          <template #default="scope">
            <span style="margin-left: 10px">{{
              scope.row.isReturn ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否丢失">
          <template #default="scope">
            <span style="margin-left: 10px">{{
              scope.row.isLost ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        v-model:current-page="bookPage"
        :total="borrowBooks.data.length"
        page-size="4"
        layout="total,prev, pager, next,jumper"
      />
      <template #footer>
        <el-button @click="borrowShow = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="addAccount" title="新增读者" width="30%">
      <el-alert
        type="warning"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
      >
        <p>所有参数不能为空！</p>
      </el-alert>
      <div class="borrow-body">
        <el-form
          :label-position="'right'"
          label-width="80px"
          style="max-width: 460px"
        >
          <el-form-item label="用户名">
            <el-input type="text" v-model="add.ReaderName"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input type="password" v-model="add.password"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="add.PhoneNumber" type="text"></el-input>
          </el-form-item>
          <el-form-item label="身份">
            <el-select v-model="add.job" class="m-2" placeholder="Select">
              <el-option
                :key="'TEACHER'"
                :label="'TEACHER'"
                :value="'TEACHER'"
              />
              <el-option
                :key="'STUDENT'"
                :label="'STUDENT'"
                :value="'STUDENT'"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="权限">
            <el-select v-model="add.authority" placeholder="Select">
              <el-option :key="0" :label="0" :value="0" />
              <el-option :key="1" :label="1" :value="1" />
              <el-option :key="2" :label="2" :value="2" />
            </el-select>
          </el-form-item> -->
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addAccounts"> 确定增加 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-pagination
      class="page"
      v-model:current-page="page"
      :total="accountList.list.length"
      layout="total,prev, pager, next,jumper"
    />
  </div>
</template>

<script setup>
import { ref, onBeforeMount, reactive, watch } from "vue";
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  get,
  post_form,
  post_json,
  deLete,
  put,
  pagination,
} from "../../stores/requestMethod";
const selectList = [
  {
    value: "name",
    label: "用户名",
  },
  {
    value: "id",
    label: "id",
  },
];
const accountInfo = reactive({
  data: {
    ReaderID: 0,
    ReaderName: "",
    Debt: "",
    job: "",
    PhoneNumber: "",
    authority: 0,
    isAdmin: false,
    password: "",
  },
});
const borrowBooks = reactive({
  data: [],
});

const loginAccount = JSON.parse(sessionStorage.getItem("loginAccount"));
const num = ref(1);
const borrowShow = ref(false);
const dialogVisible = ref(false);
const addAccount = ref(false);
const page = ref(1);
const bookPage = ref(1);
const accountList = reactive({
  list: [],
  isShow: false,
});
const showList = reactive({
  list: [],
  bookList: [],
});
const select = ref("name");
const key = ref("");
const info = () => {
  return {
    ReaderName: "",
    password: "",
    PhoneNumber: "",
    isAdmin: 0,
    job: "",
    authority: 0,
    number: 0,
    Debt: "0.00",
  };
};
const add = ref(info());
const addAccounts = () => {
  post_json("http://127.0.0.1:5000/users", JSON.stringify(add.value), (res) => {
    console.log(res);
    addAccount.value = false;
    Object.assign(add.value, info());
    getAllAccounts();
  });
};

const search = () => {
  if (key.value === "") {
    getAllAccounts();
  } else {
    if (select.value === "name") {
      get(`http://127.0.0.1:5000/users/${key.value}`, (res) => {
        accountList.list = res.data;
      });
    } else {
      get(`http://127.0.0.1:5000/users/${key.value}`, (res) => {
        accountList.list = res.data;
      });
    }
  }
};
const handleDelete = (index, row) => {
  ElMessageBox.confirm("您确定要删除吗", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    get(`http://127.0.0.1:5000/records/${row.ReaderID}`, (res) => {
      if(res.data.length > 0){
        ElMessage({
          message : '该用户有书籍未还，无法删除',
          type : 'warning'
        })
      }else{
        deLete(`http://127.0.0.1:5000/users/${row.ReaderID}`, (res) => {
          console.log(res);
          getAllAccounts();
        });
      }
    });
    
  });
};
const handleCheck = (index, row) => {
  get(`http://127.0.0.1:5000//records/${row.ReaderID}`, (res) => {
    if(res.data == null){
      ElMessage('该用户没有借书记录')
      return
    }
    console.log(res);
    borrowBooks.data = res.data;
    borrowShow.value = true;
  });
};
const handleEdit = (index, row) => {
  console.log(row);
  accountInfo.data = row;
  dialogVisible.value = true;
};
const confirmEdit = () => {
  put(
    `http://127.0.0.1:5000/users`,
    JSON.stringify(accountInfo.data),
    (res) => {
      console.log(res);
      dialogVisible.value = false;
      getAllAccounts();
    }
  );
};
const getAllAccounts = () => {
  get("http://127.0.0.1:5000/users", (res) => {
    accountList.list = res.data;
    showList.list = showList.list = pagination(
      10,
      page.value,
      JSON.parse(JSON.stringify(accountList.list))
    );
    accountList.isShow = true;
  });
};

onBeforeMount(() => {
  getAllAccounts();
});
watch(page, (value, oldValue) => {
  console.log(value, oldValue);
  getAllAccounts();
  showList.list = pagination(
    10,
    value,
    JSON.parse(JSON.stringify(accountList.list))
  );
});
watch(bookPage, (value, oldValue) => {
  console.log(value, oldValue);
  showList.bookList = pagination(
    4,
    value,
    JSON.parse(JSON.stringify(borrowBooks.data))
  );
});
</script>

<style scoped>
.search {
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 20px;
  text-align: left;
}
.page {
  position: relative;
  width: 50%;
  left: 50%;
  top: 10px;
}
.borrow-body {
  text-align: left;
  margin-left: 10%;
  width: 80%;
}
.borrow-item {
  margin-top: 10px;
}
.price {
  color: #ff5000;
}
</style>
